package com.example.grpc.provider.service;

import com.example.grpc.remote.RApiCompany;
import com.example.grpc.remote.RApiUser;
import com.example.grpc.remote.RApiUserRegisterRequest;
import com.example.grpc.remote.RApiUserRegisterResponse;
import com.example.grpc.remote.UserServiceGrpc;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author liyuncong
 * @version 1.0
 * @file RemoteUserServiceImpl
 * @brief RemoteUserServiceImpl
 * @details 远程用户服务实现
 * @date 2022-11-20
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2022-11-20               liyuncong          Created
 */
@GrpcService
public class RemoteUserServiceImpl extends UserServiceGrpc.UserServiceImplBase {

    @Override
    public void searchUsersByCompany(RApiCompany request, StreamObserver<RApiUser> responseObserver) {
        for (RApiUser rApiUser : mockUsers(10)) {
            responseObserver.onNext(rApiUser);
        }
        responseObserver.onCompleted();
    }

    @Override
    public StreamObserver<RApiCompany> searchUsersByCompanies(StreamObserver<RApiUser> responseObserver) {
        return new StreamObserver<>() {
            final List<RApiUser> users = new ArrayList<>();

            @Override
            public void onNext(RApiCompany rApiCompany) {
                final int random = new Random().nextInt(0, 20);
                users.addAll(mockUsers(random));
            }

            @Override
            public void onError(Throwable throwable) {
                users.clear();
            }

            @Override
            public void onCompleted() {
                for (RApiUser rApiUser : users) {
                    responseObserver.onNext(rApiUser);
                }
                responseObserver.onCompleted();
            }
        };
    }

    @Override
    public void register(RApiUserRegisterRequest request, StreamObserver<RApiUserRegisterResponse> responseObserver) {
        final RApiCompany rApiCompany = request.getRApiCompany();
        final List<RApiUser> rApiUserList = request.getRApiUserList();
        rApiUserList.forEach(System.out::println);
        responseObserver.onNext(RApiUserRegisterResponse.newBuilder().setResult(true).build());
        responseObserver.onCompleted();
    }

    private static List<RApiUser> mockUsers(int range) {
        List<RApiUser> list = new ArrayList<>();
        if (range <= 0) {
            return list;
        }
        RApiUser.Builder builder = RApiUser.newBuilder();
        for (int i = 0; i < range; i++) {
            list.add(builder
                .setUserId(i)
                .setFullName("user_" + i)
                .setUsername("user_" + i)
                .build());
        }
        return list;
    }
}
